package cn.itcast.goods.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.StatusConstant;
import cn.itcast.exception.CustomException;
import cn.itcast.exception.DeletionNotAllowedException;
import cn.itcast.goods.dto.DishDTO;
import cn.itcast.goods.dto.DishPageQueryDTO;
import cn.itcast.goods.mapper.DishFlavorMapper;
import cn.itcast.goods.mapper.DishMapper;
import cn.itcast.goods.mapper.SetmealDishMapper;
import cn.itcast.goods.mapper.SetmealMapper;
import cn.itcast.goods.pojo.Dish;
import cn.itcast.goods.pojo.Setmeal;
import cn.itcast.goods.pojo.SetmealDish;
import cn.itcast.goods.service.DishService;
import cn.itcast.goods.vo.DishVO;
import cn.itcast.result.PageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageBean pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        // 开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        page.getResult().forEach(e -> {
            e.setFlavors(dishFlavorMapper.getByDishId(e.getId()));
        });

        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 添加菜品
     *
     * @param dishDTO
     */
    @CacheEvict(cacheNames = "dish:list", allEntries = true)
    @Transactional
    @Override
    public void save(DishDTO dishDTO) {

        // 判断新增菜品名称是否已存在
        if (dishMapper.getByName(dishDTO.getName()) != null) {
            throw new CustomException(String.format(MessageConstant.ALREADY_EXISTS, dishDTO.getName()));
        }

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);

        // 设置菜品默认状态为停售
        dish.setStatus(StatusConstant.DISABLE);


        dishMapper.insert(dish);


        dishDTO.getFlavors().forEach(e -> {
            e.setDishId(dish.getId());
            dishFlavorMapper.insert(e);
        });
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @CacheEvict(cacheNames = "dish:list", allEntries = true)
    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {

        // 判断需要删除的菜品中是否包含正在售卖的菜品
        if (dishMapper.getByIdsAndStatus(ids, StatusConstant.ENABLE).size() > 0) {
            // 有菜品正在售卖,不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        // 判断需要删除的菜品中是否有套餐包含
        if (setmealDishMapper.getByDishIds(ids).size() > 0) {
            // 有套餐包含需要删除的菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        return dishMapper.getByIdWithFlavor(id);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO
     */
    @CacheEvict(cacheNames = "dish:list", allEntries = true)
    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {

        // 判断需要更新的菜品名是否已存在
        Dish byName = dishMapper.getByName(dishDTO.getName());
        if (byName != null && byName.getId() != dishDTO.getId()) {
            throw new CustomException(String.format(MessageConstant.ALREADY_EXISTS, dishDTO.getName()));
        }

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);


        dishMapper.update(dish);

        ArrayList<Long> ids = new ArrayList<>();
        ids.add(dish.getId());
        dishFlavorMapper.deleteByDishIds(ids);

        dishDTO.getFlavors().forEach(e -> {
            e.setDishId(dish.getId());
            dishFlavorMapper.insert(e);
        });


        setmealDishMapper.updateByDishIdWithNameAndPrice(dish.getId(), dish.getName(),dish.getPrice());
    }

    /**
     * 停售起售菜品
     *
     * @param status
     * @param id
     */
    @CacheEvict(cacheNames = "dish:list", allEntries = true)
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {

        // 更新指定id的菜品状态
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        dishMapper.update(dish);


        // 若菜品停售则包含该菜品的套餐更新为停售状态
        if (status == StatusConstant.DISABLE) {
            // 查询出所有包含当前菜品的菜品套餐关系记录
            List<Long> ids = new ArrayList<>();
            List<SetmealDish> setmealDishes = setmealDishMapper.getByDishIds(ids);

            // 将于包含当前菜品的套餐更新为停售状态
            Setmeal setmeal = Setmeal.builder()
                    .status(StatusConstant.DISABLE)
                    .build();
            setmealDishes.forEach(e -> {
                setmeal.setId(e.getSetmealId());
                setmealMapper.update(setmeal);
            });
        }

    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    @Cacheable(cacheNames = "dish:list", key = "#categoryId", unless = "#result == null || #result.size() == 0")
    public List<DishVO> list(Long categoryId) {
        return dishMapper.getByCategoryId(categoryId);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public Dish getById(Long id) {
        return dishMapper.getById(id);
    }


}
